import 'package:flutter/material.dart';
import 'package:mybase/base/tool/color/FFColor.dart';

///水波纹向外扩散动画
class FFWaveView extends StatefulWidget {
  Color bgColor;
  double begin;
  double end;
  Size size;
  Duration duration;
  Duration? delayed;

  FFWaveView({
    required this.bgColor,
    required this.begin,
    required this.end,
    required this.size,
    required this.duration,
    this.delayed,
  });

  @override
  _FFWaveViewState createState() => _FFWaveViewState();
}

class _FFWaveViewState extends State<FFWaveView> with SingleTickerProviderStateMixin {
  AnimationController? _controller;
  Animation<double>? _animation;

  @override
  void initState() {
    super.initState();

    if (widget.delayed != null) {
      Future.delayed(widget.delayed!, () {
        if (!mounted) {
          return;
        }
        begin();
      });
    } else {
      begin();
    }
  }

  void begin() {
    _controller = AnimationController(
      duration: widget.duration,
      vsync: this,
    )..repeat(reverse: false);

    _animation = Tween<double>(begin: widget.begin, end: widget.end).animate(_controller!);
    setState(() {});
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_animation == null) {
      return Container();
    }

    return AnimatedBuilder(
      animation: _animation!,
      builder: (BuildContext context, Widget? child) {
        return Center(
          child: CustomPaint(
            painter: CirclePainter(
              radius: _animation!.value,
              color: widget.bgColor,
              opacity: 1 - (_animation!.value - widget.begin) / (widget.end - widget.begin),
            ),
            size: widget.size,
          ),
        );
      },
    );
  }
}

class CirclePainter extends CustomPainter {
  double radius;
  Color color;
  double opacity;

  CirclePainter({
    required this.radius,
    required this.color,
    required this.opacity,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = rgba(color.red, color.green, color.blue, opacity);
    paint.style = PaintingStyle.fill;

    final center = Offset(size.width * 0.5, size.height * 0.5);
    canvas.drawCircle(center, radius, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
